package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Dorm;
import com.example.exception.CustomException;
import com.example.mapper.BuildingMapper;
import com.example.mapper.DormMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.ir.LiteralNode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 宿舍信息表业务处理
 **/
@Service
public class DormService {

    @Resource
    private DormMapper dormMapper;

    @Resource
    private BuildingMapper buildingMapper;

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(Dorm dorm) {
        // 先判断绑定的楼栋是否超过标准宿舍数
        Integer count = buildingMapper
                .selectByCondition(dorm.getBuildingId());
        if(count <= 0){
            throw new CustomException("500","当前楼栋宿舍数已满，请更换楼栋");
        }
        Dorm dbDorm = dormMapper.selectByName(dorm.getName(),dorm.getBuildingId());
        if(ObjectUtil.isNotNull(dbDorm)){
            throw new CustomException("500","当前宿舍号以存在");
        }
        dormMapper.insert(dorm);
        // 插入成功，楼栋宿舍-1
        buildingMapper.decreaseNum(dorm.getBuildingId());
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) {
        Dorm dorm = dormMapper.selectById(id);
        // 删除了宿舍，楼栋宿舍+1
        buildingMapper.increaseNum(dorm.getBuildingId());
        dormMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            dormMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateById(Dorm dorm) {
        dormMapper.updateById(dorm);
    }

    /**
     * 根据ID查询
     */
    public Dorm selectById(Integer id) {
        return dormMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Dorm> selectAll(Dorm dorm) {
        return dormMapper.selectAll(dorm);
    }

    /**
     * 分页查询
     */
    public PageInfo<Dorm> selectPage(Dorm dorm, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Dorm> list = dormMapper.selectAll(dorm);
        return PageInfo.of(list);
    }


    public List<Dorm> selectAllNames(){
        List<Dorm> list = dormMapper.selectAllNames();
        return list;
    }
}